<template>
	<view v-if="option && canvasId" class="ec-wh-100" @click="echarts.onClick" :prop="setOptionData" :change:prop="echarts.updateEcharts" :id="canvasId"></view>
</template>
<script>
export default {
	data() {
		return {
			setOptionData: false
		};
	},
	props: {
		option: {
			default: false
		},
		canvasId: {
			type: String,
			default: 'ec-canvas'
		},
		lazyLoad: {
			type: Boolean,
			default: false
		}
	},
	watch: {
		option: { // 设置参数 APP / H5 获取参数方式不一样 确保 APP H5 拿到到参数一样
			immediate: true,
			handler(val) {
				if (!val) return false;
				const { option, canvasId, lazyLoad } = this;
				this.setOptionData = {
					canvasId,
					lazyLoad,
					option,
				}
			},
		},
	},
	methods: {
		changeOption() {
			// 父组件刷新数据
			this.$emit('changeOption');
		},
		onViewClick(options) {
			this.$emit('getClickData', options);
		}
	}
};
</script>

<script module="echarts" lang="renderjs">
import echartsConfig from '@/mpvue-echarts/src/echarts-config.js';
let myChart
export default {
	data(){
		return{
			clickData: null,
			optionData: {}
		}
	},
	// #ifdef APP-PLUS 
	   //   APP 环境 要从这里拿参数 H5 不需要
	   props:['setOptionData'],
	// #endif
	watch: {
		setOptionData: { // 设置参数 APP / H5 获取参数方式不一样 确保 APP H5 拿到到参数一样
			immediate: true,
			handler(val) {
				this.optionData = val;
			},
		},
	},
	mounted() {
		if (typeof window.echarts === 'function') {
		    this.initEcharts()
		} else {
			const script = document.createElement('script')
			script.src = 'static/echarts.js'
			script.onload = this.initEcharts.bind(this)
		    document.head.appendChild(script)
		}
	},
	methods:{
		initEcharts(){
			echarts.registerTheme('echartsConfig', echartsConfig)  //注册主题
			myChart = echarts.init(document.getElementById(this.optionData.canvasId),"echartsConfig");
			// 观测更新的数据在 view 层可以直接访问到
			myChart.setOption(this.optionData.option);
		},
		updateEcharts(newValue, oldValue, ownerInstance, instance) {
			console.log('updateEcharts',newValue)
		},
		onClick(event, ownerInstance) {
			console.log('onClick', event)
			console.log('ownerInstance', ownerInstance)
			ownerInstance.callMethod('onViewClick',{
				value:this.clickData.value,
				name:this.clickData.name,
				dataIndex:this.clickData.dataIndex,
				seriesName:this.clickData.seriesName
			})
		}
	}
}
</script>

<style>
.content {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
}

.ec-wh-100 {
	width: 100%;
	height: 100%;
}
</style>
